import { useEffect } from "react";
import Vditor from "vditor";

/**
 * 
 * @param {string} initialMarkdown: markdown text 
 * @param {react setState hook} setMarkdown: set markdown text fo parent componet
 * @param {react setState hook} setBlur: set blur true
 * @param {string} editorId: used to distinguish different editor
 * 
 * More details about vditor config, see:
 * https://github.com/Vanessa219/vditor/blob/master/src/ts/util/Options.ts?utm_source=ld246.com
 */
export default function MarkdownEditor({ initialMarkdown, setMarkdown, Id, width, setBlur }) {
    const customId = Id || 'vditor';
    const md = initialMarkdown || '';
    const customWidth = width || 'auto';

    useEffect(() => {
        const vditor = new Vditor(customId, {
            after() {
                vditor.setValue(md);
            },
            input(md) {
                setMarkdown(md);
            },
            blur() {
                if (typeof setBlur === 'function') {
                    setBlur(true);
                }
            },
            height: 'auto',
            placeholder: "支持 Markdown",
            width: customWidth,
            tab: "    ",
            cache: {
                enable: false,
            },
            theme: "classic",
            toolbarConfig: {
                pin: true,
            },
            hint: {
                emoji: {
                    "+1": "👍",
                    "-1": "👎",
                    "confused": "😕",
                    "eyes": "👀️",
                    "heart": "❤️",
                    "rocket": "🚀️",
                    "smile": "😄",
                    "tada": "🎉️",
                    "heavy_check_mark": "✔️",
                    "x": "❌",
                    "construction": "🚧",
                    "bulb": "💡",
                },
            },
            toolbar: [
                "undo",
                "redo",
                "headings",
                "bold",
                "strike",
                "emoji",
                "link",
                "list",
                "ordered-list",
                "quote",
                "line",
                "code",
                "inline-code",
                "insert-before",
                "insert-after",
                "|",
                "upload",
                "table",
                "|",
                "fullscreen",
                "preview",
                "export",
                "outline",
                "info",
            ],
            preview: {
                actions: ["desktop", "mobile"],
                hljs: { lineNumber: true }
            },
        })
    }, []);

    return (
        <div id={customId}></div>
    )
}